<!--
 * @Author: your name
 * @Date: 2021-08-17 09:46:50
 * @LastEditTime: 2021-08-26 16:59:07
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \orderSystems\src\components\gou\DishTable.vue
-->
<template>
  <!-- 菜品单位复用组件 -->
  <div id="dish-table">
    <!-- 表格title -->
    <el-container>
      <el-header class="table-header">
        <div class="table-title">
          <el-row class="title-row">
            <el-col :span="14">{{ moudleName }}</el-col>
            <el-col :span="10">
              <el-row>
                <el-col :span="5">
                  <el-button
                class="btn-size"
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="changeStatus"
                >新增</el-button
              >
                </el-col>
                <el-col :span="6">
                 <el-button
                class="btn-size"
                type="danger"
                icon="el-icon-delete"
                @click="batchDelete"
                >批量删除</el-button
              >
                </el-col>
                <el-col :span="6">
                 <el-upload
                class="import-excel"
                action=""
                accept=".xlsx,.xls"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handle"
              >
               <el-button
                class="btn-size"
                type="success"
                icon="el-icon-circle-plus"
                >批量导入</el-button
              >
              </el-upload>
                </el-col>
                <el-col :span="6">
                   <el-button 
              class="btn-size" 
              type="warning" 
              icon="el-icon-remove"
              @click="batchExport"
                >批量导出</el-button
              >
                </el-col>
              </el-row>
              <AddDialog
                v-if="dialogFormVisible"
                :changeStatus.sync="dialogFormVisible"
                :dishUnitTable="dishUnitTable"
                :optionsCategory="categoryTable"
                :SpecificationTable="SpecificationTable"
                :dishTasteTable="dishTasteTable"
                :rowIdData="rowIdData"
                :munuFileId="munuFileId"
                :flag="flag"
              ></AddDialog>
            </el-col>
          </el-row>
        </div>
      </el-header>
    </el-container>
    <!-- 表格数据 -->
    <el-container>
      <el-main class="table-content">
        <div class="table-bgc">
          <div class="table-padding">
            <el-table
              ref="multipleTable"
              :data="tableData"
              tooltip-effect="dark"
              border
              @selection-change="handleSelectionChange"
              class="table-box"
            >
              <el-table-column type="selection" width="55" align="center">
              </el-table-column>
              <el-table-column label="序号" width="120" align="center">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="菜品名称" width="150" align="center">
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
              <el-table-column label="菜品编号" width="150" align="center">
                <template slot-scope="scope">{{ scope.row.dish_no }}</template>
              </el-table-column>
              <el-table-column label="菜品单价" width="150" align="center">
                <template slot-scope="scope">{{
                  scope.row.price.toFixed(2)
                }}</template>
              </el-table-column>
              <el-table-column label="菜品类别" width="200" align="center">
                <template slot-scope="scope">{{ scope.row.category }}</template>
              </el-table-column>
              <!-- <el-table-column
                prop="remarks"
                label="备注"
                show-overflow-tooltip
                align="center"
              >
              </el-table-column> -->
              <el-table-column label="状态" width="100" align="center">
                <template slot-scope="scope">{{
                  scope.row.status == 0 ? "正常" : "待开发"
                }}</template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    plain
                    @click="handleEdit(scope.row.id)"
                    icon="el-icon-edit"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="warning"
                    plain
                    @click="handleDelete(scope.row.id)"
                    icon="el-icon-delete"
                    >删除</el-button
                  >
                  <!-- <el-dialog
                    title="编辑"
                    :visible.sync="dialogFormVisible1"
                    center
                    width="30%"
                    top="30vh"
                  >
                    <el-form :model="editForm">
                      <el-form-item
                        label="类别名称:"
                        :label-width="formLabelWidth"
                      >
                        <el-input
                          clearable
                          v-model="editForm.name"
                          autocomplete="off"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="备注:" :label-width="formLabelWidth">
                        <el-input
                          clearable
                          v-model="editForm.remarks"
                          type="textarea"
                          :rows="4"
                          autocomplete="off"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="状态" :label-width="formLabelWidth">
                        <el-switch
                          v-model="editForm.status"
                          active-color="#13ce66"
                          inactive-color="#9E99B9"
                        >
                        </el-switch>
                      </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                      <el-button @click="cancelEdit">取 消</el-button>
                      <el-button type="primary" @click="defineEdit"
                        >确 定</el-button
                      >
                    </div>
                  </el-dialog> -->
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
//导入增加菜品的组件
import AddDialog from "../../components/gou/AddDialog";
//导入execl文件
import exportExcel from '../../excel/exportExcel.js'
import {readFile,character} from '../../excel/utils.js';
import xlsx from 'xlsx';
export default {
  data() {
    return {
      multipleSelection: [],
      dialogFormVisible: false,
      dialogFormVisible1: false,
      nowPageDataAll: 0, //当前点击页的数据条数
      nowPage: 0, //当前点击页
      munuFileId: 0, //点击编辑行数据的id
      editForm: {
        //对话框弹窗相应的数据对象
        name: "", //类别名称
        remarks: "", //备注
        status: "false", //状态
      },
      formLabelWidth: "80px", //对话框内容的宽度
      dishUnitTable: [], //查询菜品单位数据数组
      categoryTable: [], //菜品类别名数据数组
      SpecificationTable: [], //菜品规格数据数组
      dishTasteTable: [], //查询菜品口味数据数组
      rowIdData: {}, //id查询的一行数据
      flag: false, //点击的是修改则为true
      flag1: false,
      code:20000,
    };
  },
  props: {
    moudleName: {
      //模块名字
      type: String,
      default: "",
    },
    tableType: {
      //表格数据表头的菜的类型名称
      type: String,
      default: "",
    },
    tableData: {
      //父级传过来的数据
      type: Array,
    },
    clickNowPage: {
      //当前页，从父级接收
      default: 1,
      type: Number,
    },
    pageCount: {
      //每页显示数据条数，从父级接收
      default: 5,
      type: Number,
    },
    nowPageSize: {
      //当前点击页的数据条数
      default: 0,
      type: Number,
    },
  },
  methods: {
    /**
     * @description: 点击新增按钮，触发的函数
     * @param {*}
     * @return {*}
     */
    async changeStatus() {
      this.dialogFormVisible = true;
      this.flag = this.flag1;
      // this.munuFileId=0;
      // console.log(this.dialogFormVisible);
      //查询菜品单位接口，渲染菜品单位下拉菜单
      const { data: res } = await this.axios.post("/dishUnit/findUnit"); //这个接口网络繁忙
      // console.log('菜品单位',res);
      if (res.code == 200) {
        this.dishUnitTable = res.data;
        // console.log(res.data);
      }

      //查询菜品类别接口，渲染菜品类别下拉菜单
      const { data: res1 } = await this.axios.post(
        "/dishesCategory/findCategory"
      );
      // console.log('菜品类别',res);
      if (res1.code == 200) {
        this.categoryTable = res1.data;
        // console.log(this.categoryTable);
      }
      //查询菜品规格接口，渲染菜品规格下拉菜单
      const { data: res2 } = await this.axios.post(
        "/dishSpecification/findSpecification"
      );
      // console.log("菜品规格",res2);
      if (res2.code == 200) {
        this.SpecificationTable = res2.data;
        // console.log(res.data);
      }
      //查询菜品口味接口，渲染菜品单位下拉菜单
      const { data: res3 } = await this.axios.post("/dishTaste/findTaste");
      console.log("菜品口味", res3);
      if (res3.code == 200) {
        this.dishTasteTable = res3.data;
        // console.log(res3.data);
      }
      if (this.flag) {
        console.log("默认渲染的原始数据", this.rowIdData);
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    /**
     * @description: 获取选中行的表格数据的数组，用于批量删除
     * @param {*} val //选中的数据数组
     * @return {*}
     */
    handleSelectionChange(val) {
      //val获取选中的数据数组
      let idArr = []; //用于存储表格每行数据的id的数据
      val.forEach((item) => {
        //遍历数组，获取每条数据的id,
        idArr.push(item.id); //将id存储到新数组中
      });
      this.multipleSelection = idArr; //将新数组的值赋值给data中定义的数组
    },
    /**
     * @description: 实现批量删除函数
     * @param {*}
     * @return {*}
     */
    async batchDelete() {
      const confirm = await this.$confirm(
        //this.$fonfirm是一个promise对象，因此用async await
        "此操作将永久删除数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); //点击确认，返回confirm 点击取消，返回 cancel
      if (confirm != "confirm") {
        //如果不是点击确认，表示不删除
        this.$message({
          type: "info",
          message: "已取消删除",
          duration: "500",
        });
      } else {
        const { data: res } = await this.axios.post("/dishFile/deleteIds", {
          ids: this.multipleSelection, //删除数据的id数组
        });
        if (res.code == 200) {
          // console.log(res);
          this.$message({
            type: "success",
            message: "删除成功!",
            duration: "500",
          });
          this.$emit("shareData", {
            //通过自定义事件传值，并在父级接收值后调用初始化表格数据函数
            nowPage: this.clickNowPage,
            pageCount: this.pageCount,
          });
        } else {
          throw new console.error("删除失败");
        }
      }
    },
    /**
     * @description: 采集excel数据
     * @param {*} ev 
     * @return {*}
     */    
    async handle(ev){
      // console.log('ev',ev);
      let file =ev.raw;
      if(!file) return;
      //读取file中的数据（变为json格式）
      let data = await readFile(file);//二进制读取
      let workbook=xlsx.read(data,{type:"binary"})
      // console.log('workbook',workbook);
      let worksheet=workbook.Sheets[workbook.SheetNames[0]];
      data=xlsx.utils.sheet_to_json(worksheet);//数据转换成josn格式
      console.log('data',data);
      //把读取出来的数据变为最后可以传递给服务器的数据
      let arr=[];
      data.forEach(item=>{
        let obj={};
        arr.push(obj);
      })
      
      



    },
    /**
     * @description: 批量导出数据到excel
     * @param {*}
     * @return {*}
     */    
    batchExport(){
      let obj={
        method:'get',
        url:"/dishFile/exportFile",
        fileName:'菜品档案',
        data:this.code
      }
      exportExcel.exportMethod(obj);
    },
    /* *
     * @description: 获取表格某一行数据的id和数据
     * @param {*} id  编辑行数据的id
     * @return {*}
     */
    async handleEdit(id) {
      this.flag1 = true;
      // console.log(id);
      this.munuFileId = id;
      //根据id查询一行数据
      const { data: res } = await this.axios.get("/dishFile/findById/" + id, {
        params: {
          id: id,
        },
      });
      if (res.code == 200) {
        this.rowIdData = res.data;
        //  console.log(res.data);
        this.changeStatus(); //弹出弹框
      }

      // this.dialogFormVisible1 = true;
    },
    cancelEdit() {},
    defineEdit() {},
    /**
     * @description: 根据id删除表格一行的数据的函数
     * @param {*}
     * @return {*}
     */
    async handleDelete(id) {
      console.log(id);
      const confirm = await this.$confirm(
        //this.$fonfirm是一个promise对象，因此用async await
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); //点击确认，返回confirm 点击取消，返回 cancel
      if (confirm != "confirm") {
        //如果不是点击确认，表示不删除
        this.$message({
          type: "info",
          message: "已取消删除",
          duration: "500",
        });
      } else {
        //确认删除时发起ajax请求，删除数据
        this.axios
          .get("/dishFile/delete/" + id)
          .then((res) => {
            //  console.log(res);
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
                duration: "500",
              }); //后面将props值赋值给data中的相应值再修改，主要是因为pros中的值不能修改
              this.nowPageDataAll = this.nowPageSize - 1; //data里面定义的当前页数据-1后的值
              if (this.nowPageDataAll == 0) {
                //当前页数据删完时
                this.nowPage = this.clickNowPage; //首先讲props中的当前页页面赋值给data中的当前页页面
                this.nowPage = this.nowPage - 1; //页码-1,回到上一页
                if (this.nowPage <= 0) {
                  this.nowPage = 1; //只有一页时就在第一页
                }
              } else {
                this.nowPage = this.clickNowPage; //当前页没删完时，就在当前页
              }
              this.$emit("shareData", {
                //子传父自定义事件
                nowPage: this.nowPage,
                pageCount: this.pageCount,
              });
            }
          })
          .catch((err) => err);
      }
    },
  },
  components: {
    //注册组件
    AddDialog,
  },
};
</script>

<style lang='less' scoped>
.table-header {
  padding: 0;
  & > .table-title {
    margin: 1rem;
    background-color: #f5f9fc;
    box-sizing: border-box;
    height: 4rem;
    & > .title-row {
      line-height: 4rem;
      padding-left: 1rem;
      color: #666;
      font-weight: 500;
    }
  }
}
.btn-size {
  height: 3rem;
  padding: 0.6rem 2rem;
}
.import-excel{
  width: 11.7rem;
}
.table-content {
  padding: 0;
  & > .table-bgc {
    margin: 0 1rem 1rem;
    background-color: #f5f9fc;
    // height: 50rem;
    overflow: hidden;
    box-sizing: border-box;
    & > .table-padding {
      margin: 1rem;
    }
  }
}
</style>
